<template>
    <a-form class="smart-query-form" v-privilege="'oa:enterprise:query'">
        <a-row class="smart-query-form-row">


            <a-form-item label="应用名称" class="smart-query-form-item">
                <a-input-search style="width: 300px" v-model:value="queryForm.appName" placeholder="请输入应用名称"
                    enter-button="选择" @search="openAppTable" />
            </a-form-item>
            <a-form-item label="资源名称" class="smart-query-form-item">
                <a-input style="width: 300px" v-model:value="queryForm.resourceName" placeholder="请输入资源名称" />
            </a-form-item>

            <a-form-item class="smart-query-form-item smart-margin-left10">
                <a-button-group>
                    <a-button type="primary" @click="onSearch">
                        <template #icon>
                            <SearchOutlined />
                        </template>
                        查询
                    </a-button>
                    <a-button @click="resetQuery">
                        <template #icon>
                            <ReloadOutlined />
                        </template>
                        重置
                    </a-button>
                </a-button-group>
            </a-form-item>
        </a-row>
    </a-form>

    <a-card size="small" :bordered="false" :hoverable="true">
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">

                <a-button type="primary" @click="add">
                    新增
                </a-button>
                <a-button type="primary" danger @click="handleDelete(null)">删除</a-button>
            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.APPLICATIONMANAGEMENT.ID"
                    :refresh="ajaxQuery" />
            </div>
        </a-row>
        <a-row>
            <a-col :span="6">
                <a-tree :tree-data="treeData" v-model:selectedKeys="selectedKeys">
                </a-tree>
            </a-col>
            <a-col :span="18">
                <a-table size="small" rowKey="id" :dataSource="tableData" :columns="columns" :pagination="false"
                    :loading="tableLoading" bordered
                    :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
                    <template #bodyCell="{ column, record, text, index }">
                        <template v-if="column.dataIndex === 'index'">
                            {{ index }}
                        </template>
                    </template>
                    <template #operation="{ record }">
                        <!-- <a-button type="text" style="margin-right: 10px;">编辑</a-button> -->
                        <a-button size="small" type="link" style="margin-right: 10px;"
                            @click="upData(record)">编辑</a-button>
                        <a-dropdown>
                            <template #overlay>
                                <a-menu>
                                    <a-menu-item :key="1">
                                        <a-button type="link" danger @click="handleDelete(record)">删除</a-button>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                            <a-button type="link" size="small">
                                更多
                                <DownOutlined />
                            </a-button>
                        </a-dropdown>

                    </template>
                </a-table>
            </a-col>
        </a-row>


        <div class="smart-query-table-page">
            <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="queryForm.pageSize" v-model:current="queryForm.pageNumber"
                v-model:pageSize="queryForm.pageSize" :total="total" @change="ajaxQuery" @showSizeChange="ajaxQuery"
                :show-total="(total) => `共${total}条`" />
        </div>
        <!-- <EnterpriseOperate ref="operateRef" @refresh="ajaxQuery" /> -->
    </a-card>
    <AppTable ref="appTableRef" v-model:value="selectedRowKeyList" @change="appTableChange"></AppTable>
    <FormTemplate ref="formTemplateRef"></FormTemplate>
</template>
<script setup>
import { reactive, ref, onMounted, toRaw } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { useRouter } from 'vue-router';
import { smartSentry } from '/@/lib/smart-sentry';
import { defaultTimeRanges } from '/@/lib/default-time-ranges';
import TableOperator from '/@/components/support/table-operator/index.vue';
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
import { applicationManagementApi } from '/@/api/system/applicationManagement-api'
import AppTable from './components/app-table.vue'
import FormTemplate from './components/form.vue'
import { resourcesApi } from '/@/api/permissions/resources'

const appTableRef = ref(null)
const formTemplateRef = ref(null)
// --------------------------- 树形数据 ---------------------------
const selectedKeys = ref([]);
JSON.stringify
const treeData = ref([]);
// --------------------------- 企业表格 列 ---------------------------

const columns = ref([
    {
        title: '序号',
        dataIndex: 'index',
        width: 50,
        align: 'center'
    },
    {
        title: '图标',
        dataIndex: 'iconBase64',
        width: 100,
        ellipsis: true
    },
    {
        title: '应用名称',
        dataIndex: 'appName',
        width: 100,
        ellipsis: true
    },
    {
        title: '协议',
        dataIndex: 'protocol',
        width: 100,
        ellipsis: true
    },
    {
        title: '分类',
        dataIndex: 'category',
        width: 100,
        ellipsis: true
        // fixed: 'right',
    },
    {
        title: '排序',
        dataIndex: 'sortIndex',
        width: 100,
        ellipsis: true
    },
    {
        title: '状态',
        dataIndex: 'status',
        width: 100,
        ellipsis: true
        // fixed: 'right',
    },
    {
        title: '操作',
        dataIndex: 'operation',
        width: 150,
        slots: { customRender: 'operation' },
    },
]);

const protocolOption = ref([
    { label: 'ALL', value: '' },
    { label: 'OAuth_v2.0', value: 'OAuth_v2.0' },
    { label: 'OAuth_v2.1', value: 'OAuth_v2.1' },
    { label: 'OpenID Connect v1.0', value: 'OpenID Connect v1.0' },
    { label: 'SAML v2.0', value: 'SAML v2.0' },
    { label: 'CAS', value: 'CAS' },
    { label: 'JWT', value: 'JWT' },
    { label: 'Token Based', value: 'Token Based' },
    { label: 'Form Based', value: 'Form Based' },
    { label: 'Extend API', value: 'Extend API' },
    { label: 'Basic', value: 'Basic' },
])
// --------------------------- 查询 ---------------------------

const queryFormState = {
    pageNumber: 1,
    pageSize: PAGE_SIZE,
    searchCount: true,
    appName: '',
    resourceName: '',
    appId:''
};
const queryForm = reactive({ ...queryFormState });
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref(0);

// 日期选择
const searchDate = ref();

function dateChange(dates, dateStrings) {
    console.log(dateStrings);
    queryForm.startTime = dateStrings[0];
    queryForm.endTime = dateStrings[1];
}
// 查询
function onSearch() {
    queryForm.pageNumber = 1;
    ajaxQuery();
}
// 重置查询
function resetQuery() {
    searchDate.value = [];
    Object.assign(queryForm, queryFormState);
    ajaxQuery();
}
function dateToSeconds(dateStr) {
    if (dateStr == "") {
        return ""
    }
    let date = new Date(dateStr);
    return date.getTime() / 1000;
}
// 列表数据获取
async function ajaxQuery() {
    try {
        tableLoading.value = true;
        let responseModel = await resourcesApi.getList(queryForm);
        const list = responseModel.data.rows
        total.value = responseModel.data.records;
        tableData.value = list;
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        tableLoading.value = false;
    }
}

// 选择列表
function openAppTable() {
    appTableRef.value.showModal();
}

// --------------------------- 增加、修改、详情 ---------------------------

let router = useRouter();
const applicationFormRef = ref(null);
function handleMenuClick(key) {
    console.log(key)
    applicationFormRef.value.showDrawer(null, key.key, '新增');
}
function add() {
    formTemplateRef.value.showModal();
}
function upData(record) {
    //     const addType = ref([
    //     { name: 'OAuth2.x' },
    //     { name: 'SAML2.0' },
    //     { name: 'CAS认证' },
    //     { name: 'JWT令牌' },
    //     { name: '令牌认证' },
    //     { name: '表单认证' },
    //     { name: 'API扩展认证' },
    //     { name: '基本登录' },
    // ])
    // { label: 'OAuth_v2.0', value: 'OAuth_v2.0' },
    //     { label: 'OAuth_v2.1', value: 'OAuth_v2.1' },
    //     { label: 'OpenID Connect v1.0', value: 'OpenID Connect v1.0' },
    //     { label: 'SAML v2.0', value: 'SAML v2.0' },
    //     { label: 'CAS', value: 'CAS' },
    //     { label: 'JWT', value: 'JWT' },
    //     { label: 'Token Based', value: 'Token Based' },
    //     { label: 'Form Based', value: 'Form Based' },
    //     { label: 'Extend API', value: 'Extend API' },
    //     { label: 'Basic', value: 'Basic' },
    //     if(record){

    //     }
    applicationFormRef.value.showDrawer(record, 0, '编辑');
    // applicationFormRef.value.showDrawer(null, key.key);
}
function handleDelete(value) {
    Modal.confirm({
        title: () => '确定要删除吗?',
        content: () => '删除后不可恢复',
        onOk() {
            if (value) {
                applicationManagementApi.delete({ ids: value.id }).then(res => {
                    if (res.code === 0) {
                        message.success('删除成功！')
                        ajaxQuery();
                    }
                })
            } else if (selectedRowKeyList.value.length) {
                console.log(selectedRowKeyList.value)
                applicationManagementApi.delete({ ids: selectedRowKeyList.value.join(',') }).then(res => {
                    if (res.code === 0) {
                        message.success('删除成功！')
                        ajaxQuery();
                    }
                })
            }

        },
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onCancel() { },
    });

}

// 获取分类下拉
const FindList = ref([])
async function getFindList() {
    try {
        let res = await applicationManagementApi.queryFindList();
        FindList.value = res.data.map(item => {
            return {
                label: item.name,
                value: item.id
            }
        })
        FindList.value.unshift({ label: 'ALL', value: '' })
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
    }
}
// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
}
function appTableChange(records) {
    queryForm.appName = selectedRowKeyList.value[0];
    queryForm.appId = records[0].id;
    ajaxQuery();
    getTree();
}
// 获取树形数据
function getTree() {
    resourcesApi.getTree(queryForm).then(res => {
        if(res.data.nodes.length){
            res.data.rootNode['children'] = res.data.nodes
        }
        treeData.value = [res.data.rootNode]
    })
}
onMounted(() => {
    ajaxQuery();
    getFindList();
});
</script>